import { System } from "./System";
import { Register } from "../register/Register";
import { EventType } from "../event/index";
import { ComponentType } from "../component/Component";
/**
 * @class
 * @extends w.system.System
 * @memberof w.system
 */
class IdleSystem extends System {
    constructor(opts = {}) {
        // opts.eventType = EventType.FrameCompleted;
        super(opts);

    }
    run(event) {
        if (event.componentType === ComponentType.Destroy) {
            if (this.requestId) {
                window.cancelIdleCallback(this.requestId);
            }
            this.requestId = window.requestIdleCallback(this.idle.bind(this));
        }

    }
    idle(deadline) {
        let meshRender = Register.instance.manager(ComponentType.MeshRender).get("x");
        const destroyComs = [...Register.instance.manager(ComponentType.Destroy).components.values()];
        let hasDo = 0;
        if (destroyComs.length <= 0) { return }
        while (deadline.timeRemaining() > 0) {
            const curData = destroyComs.shift()
            if (curData) {
                const eid = [...curData.eids][0]
                if (!eid) {
                    continue;
                }
                let group = Register.instance.entityManager.get(eid);
                if (group) {
                    group.destroy(false, true);
                    // console.log(1111);
                    hasDo++
                }
            }else{
                break
            }
        }
        if (destroyComs.length > 0) {
            if (this.requestId) {
                window.cancelIdleCallback(this.requestId);
            }
            this.requestId = window.requestIdleCallback(this.idle.bind(this));
        }
        if (hasDo > 0) {
            meshRender.update("value");
        }
    }
}

export { IdleSystem }